<?php

namespace App\Services;

use App\Exceptions\BaseException;
use App\Models\MemberOther;
use App\Models\Order;
use App\Models\OrderCredit;
use App\Models\OrderGoods;
use App\Models\OrderLease;
use PhpOffice\PhpWord\TemplateProcessor;
use PhpOffice\PhpWord\IOFactory;
class RiskService
{
    public static  function booleData($input){
        $name = $input['cert_name'];   //姓名
        $number = $input['cert_no'];   //身份证号
        $phone = $input['mobile'];   //手机号

        $key = config('boolean.dlz_aes_secret');   //AES密钥
        $url = config('boolean.host_url');


        $licenseUrl=self::licenseDlzUrl($input['orderId']);
        $user = array(
            'name' => $name,
            'ident_number' => $number,
            'phone' => $phone,
            'mode' => 'mode_duolai',
            'service' => 'risk_report_service',
            'licenseUrl'=>$licenseUrl,
            'licenseType'=>'1',
        );


        $jsonData = json_encode($user);
        $jsonBaseData = self::encrypt($jsonData,$key,$iv='');  //AES加密(biz_data)

        $data = array(
            'institution_id' => config('boolean.dlz_institution_id'),		//平台唯一标识
            'charset' => 'UTF-8',		//字符类型
            'sign_type' => 'RSA2',		//加密类型
            'sign' => '',  //签名
            'timestamp' => time(),     //请求时间戳
            'version' => 'V1.0.1',		//版本
            'biz_data' => $jsonBaseData	//加密数据
        );
        $paramstring = http_build_query($data);
        $content = self::buerCurl($url,$paramstring);
        $result = json_decode($content,true);  //返回结果
//        dd($result);
        return $result;
    }

    public static function licenseDlzUrl($orderId){
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $order = Order::from('sp_order_2 as o')->where('o.id',$orderId)
            ->leftjoin('sp_member_2 as m','m.id','o.uid')
            ->select(
                'o.id','o.uid','o.mobile as user_mobile','o.pact_url_5','o.trade_no'
                ,'m.cert_name','m.cert_no'
                ,'m.mobile','m.esign_user_id','m.esign_seal_id','m.user_id','m.idcard_front','m.idcard_back'
            )
            ->first();
        if($order['pact_url_5']){
            return 'https://shouwei.oss-cn-shanghai.aliyuncs.com/approve_files/'.$order['pact_url_5'];
        }
            $result = EsignService::addPersonAccountID($order['cert_no'],$order['cert_name'],$order['cert_no'],$order['user_mobile']);
            $data1 = $result['data'];
            if(!empty($data1['accountId'])){
                $esign_user_id = $data1['accountId'];
                $order['esign_user_id'] = $esign_user_id;
            }else{
                return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同签署账号创建失败');
            }


        $result=EsignService::createBoolDlzUserAuth($order);

        $flow_id=$result['data']['flowId'];

        for ($i=0;$i<20;$i++){
            sleep(2);
            $return_content = EsignService::downloadDocument($flow_id);
            if(!isset($return_content['fileUrl']) || empty($return_content['fileUrl'])){
                sleep(2);
            }else if($return_content && !empty($return_content['fileUrl'])){
                break;
            }
        }

        if($return_content && !empty($return_content['fileUrl'])){
            $fileUrl = $return_content['fileUrl'];
            $fileName = $flow_id.".pdf";
            $file = file_get_contents($fileUrl);
            $path = dirname(dirname((dirname(__FILE__)))) . '/storage/tmp/'.$fileName;

            $file_put_res=file_put_contents($path,$file);
            if($file_put_res){
                $uploud_res = AlipayService::boolUpload($fileName,$path);
                if($uploud_res['status']){
                    if(file_exists($path)){
                        unlink($path);
                    }
                }
                $order_sign['flow_id_5'] = $flow_id;
                $order_sign['pact_url_5'] = $fileName;

                Order::where('id',$order['id'])->update($order_sign);
                return 'https://shouwei.oss-cn-shanghai.aliyuncs.com/approve_files/'.$fileName;
            }else{
                $error = error_get_last();
               throw new BaseException('文件上传失败'. $error['message']);
            }

        }

    }

    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string  b百荣
     */
    static private function buerCurl($url,$data=null){
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
        if(!empty($data)){
            curl_setopt($curl,CURLOPT_POST,1);
            curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
        }
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        //下面这行是修改后增加的代码，就是配置设置host访问，发送的数据类型为application/json
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/x-www-form-urlencoded;charset=utf-8',
            'Content-Length: ' . strlen($data)
        ));
        $output = curl_exec($curl);
        \Illuminate\Support\Facades\Log::channel("otherlog")->info("boolcurl:".json_encode(['url'=> $url,'data'=>$data,'output'=> $output]));
        curl_close($curl);
        return $output;
    }

    //RAS签名
    //private.pem-  私钥文件路已经
    static public function sign($data)
    {
        $private_key = "./cert/boobleRisk.pem";  //私钥路径
        $pkeyid = openssl_pkey_get_private(file_get_contents($private_key));
        $verify = openssl_sign($data, $signature, $pkeyid, OPENSSL_ALGO_MD5);
        openssl_free_key($pkeyid);
        return base64_encode($signature);
    }
    //签名处理
    static public function getSignString($params){
        unset($params['sign']);
        ksort($params);
        reset($params);

        $pairs = array();
        foreach ($params as $k => $v) {
            if(!empty($v)){
                $pairs[] = "$k=$v";
            }
        }

        return implode('&', $pairs);
    }

    /**
     * 加密字符串 AES
     * @param string $encrypt 字符串
     * @param string $key     加密key 16位
     * @param string $iv      加密向量 16位
     * @return string
     */
    static public function encrypt( $encrypt, $key, $iv ) {
        $base_encrypt = base64_encode($encrypt);
        $data = openssl_encrypt($encrypt, 'AES-128-ECB', $key, 0, $iv);
        return $data;
    }


    public static function goodsConfirmPdf($orderId){
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $order = Order::from('sp_order_2 as o')->where('o.id',$orderId)
            ->leftjoin('sp_member_2 as m','m.id','o.uid')
            ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
            ->leftjoin('sp_order_return_2 as or','o.id','or.order_id')
            ->select(
                'o.id','o.uid','o.mobile as user_mobile','o.pact_url_5','o.trade_no','og.id as order_goods_id'
                ,'m.cert_name','m.cert_no','og.goods_confirm_pdf','or.confirm_time','og.goods_title','og.setmeal_title'
                ,'m.mobile','m.esign_user_id','m.esign_seal_id','m.user_id','m.idcard_front','m.idcard_back','og.device_number','or.delivery_type'
            )
            ->first();
        if($order['goods_confirm_pdf']){
            return config('alipay.oss.imgHost').$order['goods_confirm_pdf'];
        }
        if(empty($order['confirm_time'])){
            throw new BaseException("订单未签收！");
        }
        if(empty($order['esign_user_id'])){
            $result = EsignService::addPersonAccountID($order['cert_no'],$order['cert_name'],$order['cert_no'],$order['user_mobile']);
            $data1 = $result['data'];
            if(!empty($data1['accountId'])){
                $esign_user_id = $data1['accountId'];
                MemberOther::where('id',$order['uid'])->update(['esign_user_id'=>$esign_user_id]);
            }else{
                throw new BaseException("合同签署账号创建失败！");
            }
        }else{
            $user_mobile = !empty($order['user_mobile'])?$order['user_mobile']:$order['mobile'];
            $esign_user_id = EsignService::updateAccounts($order['esign_user_id'],$user_mobile,$order['cert_name']);
            if(empty($esign_user_id)){
                $result = EsignService::addPersonAccountID($order['cert_no'],$order['cert_name'],$order['cert_no'],$order['user_mobile']);
                $data1 = $result['data'];
                if(!empty($data1['accountId'])){
                    $esign_user_id = $data1['accountId'];
                    MemberOther::where(['id'=>$order['uid']])->update(['esign_user_id'=>$esign_user_id]);
                    $order['esign_user_id'] = $esign_user_id;
                }else{
                    return ReturnMsg(CommonService::HTTP_CODE_FAIL, '合同签署账号创建失败');
                }
            }
        }


        $result=EsignService::createUserGoodsConfirmAuth($order);

        $flow_id=$result['data']['flowId'];

        for ($i=0;$i<20;$i++){
            sleep(2);
            $return_content = EsignService::downloadDocument($flow_id);
            if(!isset($return_content['fileUrl']) || empty($return_content['fileUrl'])){
                sleep(2);
            }else if($return_content && !empty($return_content['fileUrl'])){
                break;
            }
        }
//        var_dump($return_content);
        if($return_content && !empty($return_content['fileUrl'])){
            $fileUrl = $return_content['fileUrl'];
            $fileName = $flow_id.".pdf";
            $file = file_get_contents($fileUrl);
            $path = dirname(dirname((dirname(__FILE__)))) . '/storage/tmp/'.$fileName;

            file_put_contents($path,$file);
            $uploud_res = AlipayService::upload($fileName,$path);
            if($uploud_res['status']){
                if(file_exists($path)){
                    unlink($path);
                }
            }
            $order_sign['goods_confirm_pdf'] = $fileName;

            OrderGoods::where('id',$order['order_goods_id'])->update($order_sign);
            return  config('alipay.oss.imgHost').$fileName;
        }

    }


}
